package com.ikingtech.framework.sdk.call.huawei;

import com.ikingtech.framework.sdk.context.exception.FrameworkException;
import com.ikingtech.framework.sdk.utils.Tools;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @author tie yan
 */
public class Signature {

    private Signature() {
        // do nothing
    }

    public static String build(String appKey, String secretKey) {
        if (Tools.Str.isBlank(appKey) || Tools.Str.isBlank(secretKey)) {
            throw new FrameworkException("[Huawei-private call]invalid appKey and secretKey");
        }
        String time = Tools.DateTime.Formatter.utc();
        String nonce = Tools.Id.uuid().toUpperCase();
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            return Tools.Str.format("UsernameToken Username=\"{}\",PasswordDigest=\"{}\",Nonce=\"{}\",Created=\"{}\"", appKey, new String(Base64.getEncoder().encode(mac.doFinal((nonce + time).getBytes(StandardCharsets.UTF_8))), StandardCharsets.UTF_8), nonce, time);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            throw new FrameworkException("[Huawei-private call]signature fail");
        }
    }
}
